package licode.unisop.client.service.impl;

import licode.unisop.client.api.SopPlatform;
import licode.unisop.client.api.SopPlatformAuth;
import licode.unisop.client.api.SopPlatformMng;
import licode.unisop.client.info.SopIdInfo;
import licode.unisop.client.utils.SopAuthConst;
import licode.unisop.client.utils.SopRequestParse;
import licode.unisop.client.utils.StringUtil;
import licode.unisop.client.vo.SopAuthPlatform;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * Sso单点登录检查
 *
 * @author WR
 * @since 2016/6/14 19:40
 */
@Component
public class SopAuthCheck {
    @Resource
    private SopPlatformMng platformMng;

    @Resource
    private SopPlatformAuth sopPlatformAuth;

    @Value("${uni-sop.token-name:platform}")
    private String platformName;

    public String getPlatformId(HttpServletRequest request) {
        return SopRequestParse.getValue(request, platformName);
    }

    public SopPlatform getPlatformById(String platId) {
        return platformMng.getPlatform(platId);
    }

    public SopPlatform getPlatformById(HttpServletRequest request) {
        String platId = SopRequestParse.getValue(request, platformName);
        return platformMng.getPlatform(platId);
    }

    public SopAuthPlatform getPlatform(HttpServletRequest request) {
        SopPlatform platform = null;
        String id = SopRequestParse.getPlatformId(request);

        if (StringUtil.isNotBlank(id)) {
            platform = platformMng.getPlatform(id);
        }

        if (null == platform && !SopAuthConst.PLATFORM_TOKEN.equals(id)) {
            id = SopRequestParse.getValue(request, platformName);
            platform = platformMng.getPlatform(id);
        }

        if (null != platform) {
            return platform.getAuthPlatform();
        } else if (StringUtil.isNotBlank(id)) {
            return sopPlatformAuth.fromId(SopIdInfo.builder().id(id).build());
        } else {
            return null;
        }
    }
}
